﻿@using System.Globalization;
@{
    var id = ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
    var name = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
    var strValue = Value;

    var attributes = CommonHelper.ObjectToDictionary(ViewData["htmlAttributes"] ?? new object());
    attributes["data-select-url"] = Url.Action("AllStores", "Store", new { selectedIds = strValue, area = "admin" });
    attributes["data-select-init-load"] = strValue.HasValue().ToString().ToLower();

    if (!attributes.ContainsKey("data-placeholder"))
    {
        attributes["data-placeholder"] = T("Admin.Common.StoresAll").Text;
    }
    if (!attributes.ContainsKey("multiple") && GetMetadata<bool>("multiple"))
    {
        attributes["multiple"] = "multiple";
    }
}
<select id="@id" name="@name" class="form-control" @Html.Attrs(attributes)></select>
<script>
    $(function () {
        $('#@id').selectWrapper();
    });
</script>

@functions
{
    private string Value
    {
        get
        {
            if (ViewData.Model != null)
            {
                // Be careful with the conversion here because it's very vulnerable to errors.
                if (ViewData.Model is int[])
                {
                    return string.Join(",", ViewData.Model);
                }

                if (CommonHelper.TryConvert(ViewData.Model, typeof(string), CultureInfo.InvariantCulture, out object obj) && obj != null)
                {
                    return obj.ToString();
                }
            }

            return null;
        }
    }
}
